package org.example.designmodel.masterwork;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

public class Worker<T extends Task, R> {

    private LinkedBlockingDeque<T> queue = new LinkedBlockingDeque<>();

    static AtomicInteger counter = new AtomicInteger(0);

    private Thread thread;

    private int id;

    public Worker() {
        this.id = counter.getAndIncrement();
        this.thread = new Thread(() -> this.execute());
        this.thread.start();
    }

    public void execute() {
        // 死循环，从队列里面获取任务执行
        for (;;) {
            try {
                Task task = queue.take();
                task.setWorkerId(this.id);
                task.execute();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void submit(T t, Consumer<R> action) {
        t.action = action;
        queue.add(t);
    }

    public int getId() {
        return id;
    }
}
